package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		String username = req.getParameter("username");
		String pw = req.getParameter("password");
			
		String msg = "";
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		try 
		{
			if(username.isEmpty()||pw.isEmpty())
			{
				//auction has expired
				msg = "Error. Fields cannot be empty.";
				req.setAttribute("msg", msg);

				
				System.out.println(msg);

				req.getRequestDispatcher("error.jsp").forward(req, resp);	
			}
			else
			{
				Entity e = ds.get(KeyFactory.createKey("User", username));
				String password = e.getProperty("PASSWORD").toString();
				String type = (String) e.getProperty("TYPE");
				
				
				if(password.equals(pw))
				{
					//logged in
					req.setAttribute("username", username);
					req.setAttribute("pw", pw);
					
					if(type.equals("seller"))
					{//Seller
						req.getRequestDispatcher("sellerIndex.jsp").forward(req, resp);
					}
					else if ( type.equals("buyer"))
					{//Buyer
						req.getRequestDispatcher("buyerIndex.jsp").forward(req, resp);
					}else{
						//corrupted user type
						msg = "Error. User account is corrupted.";
						req.setAttribute("msg", msg);

						
						System.out.println(msg);

						req.getRequestDispatcher("error.jsp").forward(req, resp);	
					}
					
				}
				else
				{
					//auction has expired
					msg = "Error. Username & password combination is incorrect.";
					req.setAttribute("msg", msg);

					
					System.out.println(msg);

					req.getRequestDispatcher("error.jsp").forward(req, resp);	
				}
			}

		} catch (EntityNotFoundException e) {
			//auction has expired
			msg = "Error. No such username.";
			req.setAttribute("msg", msg);

			
			System.out.println(msg);

			req.getRequestDispatcher("error.jsp").forward(req, resp);	
		}
		
	}
}
